package rensoft.android.rpc.simpleserver;

import rensoft.android.view.grid.IGridRequest;

import static rensoft.java.lang.Lang.is;
import static rensoft.java.lang.Lang.set;

import rensoft.java.json.JSONArray;
import rensoft.java.json.JSONObject;
import rensoft.java.net.UrlBuilder;

public class SimpleServerGridRequest extends ServerRequest implements IGridRequest {

  private int from;
  private int to;
  private String fromtime;
  private int requestIndex;

  public SimpleServerGridRequest(ISimpleRpcServer server, String action) {
    super(server, action);
  }

  public int getAllCount() {
    Number allcount = data.getNumber("all_count");
    if (is(allcount)) return allcount.intValue();
    return getRows().getSize();
  }

  public String getFromTime() {
    return data.getString("fromtime");
  }

  public int getIndex() {
    return requestIndex;
  }

  public JSONObject getRow(int position) {
    return getRows().get(position).asObject();
  }

  @Override
  public UrlBuilder getUrl() {
    UrlBuilder url = super.getUrl().add("from", from).add("to", to);
    if (set(fromtime)) url.add("fromtime", fromtime);
    return url;
  }

  public void setFromTime(String fromtime) {
    this.fromtime = fromtime;
  }

  public void setIndex(int requestIndex) {
    this.requestIndex = requestIndex;
    from = requestIndex * 30;
    to = requestIndex * 30 + 30;
  }

  protected JSONArray getRows() {
    return data.get("rows").asArray();
  }

}